package com.lin.generate.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lin.generate.common.base.R;
import com.lin.generate.common.base.PageReqVO;
import com.lin.generate.common.exception.BusinessException;
import com.lin.generate.common.utill.EasyPoiUtil;
import com.lin.generate.common.utill.UUIdUtils;
import com.lin.generate.common.vo.request.UserReqVO;
import com.lin.generate.common.vo.response.UserRespVO;
import com.lin.generate.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * 用户表
 *
 * @author zhaolin
 * @date 2023-06-04
 */
@RestController
@Api(tags = "用户表管理")
@Slf4j
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    IUserService iUserService;


    /**
     * 根据id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
    public R<Boolean> deleteById(@RequestParam("id") Long id) {
        return R.ok(iUserService.removeById(id));
    }


    /**
     * 修改用户表
     *
     * @return
     */
    @PutMapping("/update")
    @ApiOperation(httpMethod = "PUT", value = "修改用户表", notes = "修改用户表")
    public R<Boolean> updateByIdUser(@RequestBody UserReqVO vo) {
        return R.ok(iUserService.update(vo));
    }

    /**
     * 分页查询
     *
     * @param pageReqVO
     * @param vo
     * @param response
     * @return
     */
    @GetMapping("/pageList")
    @ApiOperation(httpMethod = "GET", value = "分页查询或导出用户表", notes = "分页查询或导出用户表")
    public R<IPage<UserRespVO>> pageList(PageReqVO pageReqVO, UserReqVO vo, HttpServletResponse response) {
        try {
            IPage<UserRespVO> resultPage = iUserService.pageList(pageReqVO, vo);
            if (pageReqVO.getOperType() == 0L) {
                return R.ok(resultPage);
            }
            List<UserRespVO> records = resultPage.getRecords();
            String fileName = UUIdUtils.generateUUID() + ".xls";
            String title = "用户表列表";
            EasyPoiUtil.exportExcel(records, title, title, UserRespVO.class, fileName, response);
            return null;
        } catch (BusinessException e) {
            return R.fail(e.getError(), null);
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/getObject/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
    public R<UserRespVO> selectById(@PathVariable("id") Long id) {
        return R.ok(iUserService.getObjectById(id));
    }


}
